package com.rabbitmq.dead;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.util.ConnectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yinxing
 * @date 2022-08-29
 */
public class Consumer {

    private final static String NORMAL_EXCHANGE = "normal_exchange";

    private final static String NORMAL_ROUTE_KEY = "normal_key";

    private final static String NORMAL_QUEUE_NAME = "normal_queue";

    private final static String DEAD_EXCHANGE = "dead_exchange";

    private final static String DEAD_ROUTE_KEY = "dead_key";

    private final static String DEAD_QUEUE_NAME = "dead_queue";

    public static void main(String[] args) throws IOException {
        Channel channel = ConnectionUtils.getChannel();
        //声明死信和普通交换机，类型是直接交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //普通队列
        Map<String, Object> arguments = new HashMap<>();
        //设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        //死信routing-key
        arguments.put("x-dead-letter-routing-key", DEAD_ROUTE_KEY);
        channel.queueDeclare(NORMAL_QUEUE_NAME, false, false, false, arguments);
        //声明死信
        channel.queueDeclare(DEAD_QUEUE_NAME, false, false, false, null);

        //绑定普通交换机与队列
        channel.queueBind(NORMAL_QUEUE_NAME, NORMAL_EXCHANGE, NORMAL_ROUTE_KEY);
        //绑定死信
        channel.queueBind(DEAD_QUEUE_NAME, DEAD_EXCHANGE, DEAD_ROUTE_KEY);

        System.out.println("等待接收消息...");
        DeliverCallback deliverCallback = (ct, message) -> {
            String message1 = new String(message.getBody(), "UTF-8");
            System.out.println("Consumer 接收到:" + message1);
            if (Integer.valueOf(message1) % 2 == 0) {
                System.out.println("拒收偶数，放入死信队列");
                channel.basicNack(message.getEnvelope().getDeliveryTag(), false, false);
            }
        };
        channel.basicConsume(NORMAL_QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });
    }
}
